package com.sunshine.wrongquestionset.activity.me

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.LayoutInflater
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.google.android.material.snackbar.Snackbar
import com.google.android.material.textfield.TextInputEditText
import com.sunshine.wrongquestionset.R
import com.sunshine.wrongquestionset.activity.base.BaseActivity
import com.sunshine.wrongquestionset.activity.login.LoginActivity
import com.sunshine.wrongquestionset.callback.OnRefreshListener
import com.sunshine.wrongquestionset.room.entity.AppConfigEntity
import com.sunshine.wrongquestionset.utils.TagUtils
import kotlinx.android.synthetic.main.activity_me.*
import kotlinx.android.synthetic.main.activity_me.textView_userId
import kotlinx.android.synthetic.main.fragment_me.*

class MeActivity : BaseActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_me)
        setTitle(getString(R.string.label_me_info))

        val viewModel = ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory.getInstance(application)).get(MeViewModel::class.java)

        getLoginUserAppConfig(object : OnRefreshListener<AppConfigEntity>() {
            override fun onUpdate(obj: AppConfigEntity) {
                super.onUpdate(obj)

                textView_userId.text = obj.id

                viewModel.getUserById(obj.id).observe(this@MeActivity, Observer {userEntity ->
                    textView_nickname.text = userEntity?.nickname

                    nickname_view.setOnClickListener {
                        val builder = MaterialAlertDialogBuilder(this@MeActivity)
                        builder.apply {
                            val view = LayoutInflater.from(this@MeActivity).inflate(R.layout.view_add_nickname, null, false)
                            val editAddNickname: TextInputEditText = view.findViewById(R.id.edit_add_nickname)
                            //首先设置原有昵称
                            editAddNickname.setText(textView_nickname.text)

                            setPositiveButton("确定") {_, _ ->
                                if (editAddNickname.text.isNullOrBlank()) {
                                    Snackbar.make(me_root, getString(R.string.nick_empty_warning), Snackbar.LENGTH_SHORT).show()
                                } else {
                                    userEntity?.nickname = editAddNickname.text.toString()
                                    textView_nickname.text = userEntity?.nickname
                                    viewModel.updateUser(userEntity)
                                    Snackbar.make(me_root, getString(R.string.update_nickname_success), Snackbar.LENGTH_SHORT).show()
                                    setResult(TagUtils.ME_ACTIVITY)
                                }
                            }

                            setView(view)
                        }
                        builder.create().show()
                    }
                })
                //textView_nickname.text = obj.nickname

                password_view.setOnClickListener {
                    val builder = MaterialAlertDialogBuilder(this@MeActivity)
                    builder.apply {
                        val view = LayoutInflater.from(this@MeActivity).inflate(R.layout.view_update_password, null, false)
                        val editPasswordOld: TextInputEditText = view.findViewById(R.id.edit_password_old)
                        val editPassword: TextInputEditText = view.findViewById(R.id.edit_password)
                        val editPasswordAgain: TextInputEditText = view.findViewById(R.id.edit_password_again)

                        setPositiveButton("确定") {_, _ ->
                            var hasClick = false
                            //获取用户原密码
                            viewModel.getLoginUserEntity(obj.id).observe(this@MeActivity, Observer {
                                //是点击而不是更新才有下续操作
                                if (hasClick) return@Observer

                                if (editPasswordOld.text.isNullOrBlank() || editPasswordOld.text!!.toString() != it?.password) {
                                    Snackbar.make(me_root, getString(R.string.password_old_error), Snackbar.LENGTH_SHORT).show()
                                }
                                else if (editPassword.text.isNullOrBlank()) {
                                    Snackbar.make(me_root, getString(R.string.password_error), Snackbar.LENGTH_SHORT).show()
                                }
                                else if (editPasswordAgain.text.isNullOrBlank() || editPassword.text!!.toString() != editPasswordAgain.text!!.toString()){
                                    Snackbar.make(me_root, getString(R.string.password_and_password_again_error), Snackbar.LENGTH_SHORT).show()
                                }
                                else {
                                    it.password = editPassword.text.toString()
                                    viewModel.updateLoginUserEntity(it)
                                    Snackbar.make(me_root, "修改成功", Snackbar.LENGTH_SHORT).show()
                                    hasClick = true
                                }
                            })

                        }

                        setView(view)
                    }
                    builder.create().show()
                }

                button_logout.setOnClickListener {
                    val builder = MaterialAlertDialogBuilder(this@MeActivity)
                    builder.apply {
                        setTitle(getString(R.string.warning_title))
                        setMessage("是否要退出登录？退出登录后，你将无法记录题目了")
                        setPositiveButton("取消") {_, _ ->}
                        setNegativeButton("退出登录") {_, _ ->
                            obj.isLogin = false
                            viewModel.updateAppConfig(obj)
                            //结束所有活动
                            finishAllWithoutThis(this@MeActivity)
                            clearAppConfig()

                            //退出登录后跳转到登录界面
                            startActivity(Intent(this@MeActivity, LoginActivity::class.java))
                            //结束自己
                            finish()
                        }
                    }
                    builder.create().show()
                }
            }
        })
    }
}